import 'dart:io';

import 'package:flutter/material.dart';
import 'package:livan_log_tool/livan_log_tool.dart';
import 'package:archive/archive_io.dart';

class FilesView extends StatefulWidget {
  const FilesView({Key? key}) : super(key: key);

  @override
  _FilesViewState createState() => _FilesViewState();
}

class _FilesViewState extends State<FilesView> {
  List<FileSystemEntity> _fileList = [];

  @override
  void initState() {
    super.initState();
    initData().then((_) => {});
  }

  Future<void> initData() async {
    final tempFiles = await LogManager.instance.getLogs();
    setState(() {
      _fileList = tempFiles;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('日志列表'),
      ),
      body: ListView.builder(
        itemCount: _fileList.length,
        // itemExtent: 60,
        itemBuilder: _listItem,
      ),
    );
  }
  Widget _listItem(BuildContext context, int index) {
    final fileItem = _fileList[index];
    return GestureDetector(
      child: ListTile(
        title: Text(fileItem.filename),
        subtitle: Text(fileItem.fileType),
        trailing: IconButton(
          icon: const Icon(Icons.delete),
          onPressed: () async {
            try {
              await LogManager.instance.deleteLog(fileItem.path);
              var tempFileList = [..._fileList];
              tempFileList.removeAt(index);
              setState(() {
                _fileList = tempFileList;
              });
            } catch (e) {

            }
          },
        ),
      ),
      onTap: () async {
        Navigator.pushNamed(context, "/log_detail", arguments: fileItem);
      },
      onLongPress: () async {
        // Zip a directory to out.zip using the zipDirectory convenience method
        var encoder = ZipFileEncoder();
        final doc = await LogManager.instance.documentPath();
        encoder.zipDirectory(Directory(doc), filename: '${doc}/zip_${fileItem.filename}.zip');
      },
    );
  }
}
